#!/bin/bash
## written by Aiker.
#
#chkconfig: 2345 80 90
#
# description:  Starts, stops and restart autossh service
#
# autossh startup Script
 
export autossh=/bin/autossh
export AUTOSSH_LOGFILE=/tmp/autossh.log
export AUTOSSH_PIDFILE=/var/run/autossh.pid
export AUTOSSH_POLL=180
export AUTOSSH_FIRST_POLL=30
export AUTOSSH_GATETIME=0
export AUTOSSH_DEBUG=1
 
user="root" 
R_host="myIP"
 
 
 
start() {
     # Do not start if there is no autossh.
 
     if [ ! -x "$autossh" ];then
         echo " Fail : $autossh not found."
 
     else
 
        if [ -f "$AUTOSSH_PIDFILE" ]; then
           echo "  >>> autosh is already running ... "
        fi
 
        # 5679监视端口         12246在R_host上起的端口     22本地端口
        $autossh -M 5679 -NfR 12246:localhost:22 root@$R_host -i /home/root/.ssh/id_rsa  -o "ServerAliveInterval 300" -o "ServerAliveCountMax 5"
 
        if [ $? -eq 0 ]; then
           echo "  >>> Start autossh sucesses..."
        fi 
     fi
}
 
stop() {
     #Do not stop if not found $AUTOSSH_PIDFILE
 
     if [  -f  "$AUTOSSH_PIDFILE" ]; then
 
        export pid=$(cat "$AUTOSSH_PIDFILE")
        num=$(ps -ef|awk  '{if($2~/'$pid'/) print $2}'|wc -l)
 
       if [[ $num -gt 0  ]]; then
 
          ps -ef|awk  '{if($2~/'$pid'/) print $2}'|xargs kill
          rm -f "$AUTOSSH_PIDFILE"
          echo "  >>> Autossh stop sucesses..."
       fi
 
     else
 
        echo "  >>> Autossh not running , exit .."
 
     fi
 
}
 
status() {
 
     if [  -f  "$AUTOSSH_PIDFILE" ]; then
        export pid=$(cat $AUTOSSH_PIDFILE)
        echo "  >>> autossh-daemon (pid "$pid") is running..."
 
     else
        echo "  >>> Autossh is is stopped. "
     fi   
}
      
restart() {
 
        stop;
        start
}
 
case "$1" in 
   start)
   start
   ;;
   stop)
   stop
   ;;
   status)
   status
   ;;
   restart)
   restart
   ;;
   *)
   echo $"Usage: $0 {start|stop|status|restart}"
   exit 1
   ;;
esac
